#!/usr/bin/env python
# coding=utf-8

import re
import sys
import csv
import os

proto_str = """syntax = "proto3";

package TABLE;

message {0}
{{
{1}
}}


message {0}ARRAY
{{
	repeated {0} rows = 4;
}}
"""

dataTypeDic = {
        "int": "int32",
        "short": "int32",
        "ushort": "uint32",
        "uint": "uint32",
        "byte": "uint32",
        "long": "int64",
        "ulong": "uint64",
        "string": "string",
        "bool": "bool",
        "double": "double",
        "float": "float",
        
        "repeated uint": "repeated uint32",
        "Repeated uint": "repeated uint32",
        "repeated Uint": "repeated uint32",
        "Repeated Uint": "repeated uint32",
        "repeateduint": "repeated uint32",
        "RepeatedUint": "repeated uint32",
        "repeated uint32": "repeated uint32",
        "Repeated uint32": "repeated uint32",
        "repeated Uint32": "repeated uint32",
        "Repeated Uint32": "repeated uint32",
        "repeateduint32": "repeated uint32",
        "RepeatedUint32": "repeated uint32",

        "repeated int": "repeated int32",
        "repeated string": "repeated string",
        "repeated long": "repeated int64",
        "repeated ulong": "repeated uint64",
    }
dataCommonTypeDic = {
    "UIntPair": "UIntPair",
    "UIntPairList": "UIntPairList",
    "UIntList": "UIntList",
    "UIntListJingHao": "UIntListJingHao",
    "UIntListXiaHuaXian": "UIntListXiaHuaXian",
    "UIntListXiaHuaXianFenHao": "UIntListXiaHuaXianFenHao",
    "UIntListJingHaoMeiYuan": "UIntListJingHaoMeiYuan",
    "UIntListList": "UIntListList",

    "IntListJingHao": "IntListJingHao",
    "IntListList": "IntListList",
    "ItemDrop": "ItemDrop",
    "Range": "Range",
    "ActivityAwardList": "ActivityAwardList",
    "IntPair": "IntPair",
    "IntPairList": "IntPairList",
    "IntList": "IntList",
    "StringList": "StringList",
    "IntListXiaHuaXian": "IntListXiaHuaXian",
    "IntListXiaHuaXianFenHao": "IntListXiaHuaXianFenHao",
    "IntListJingHaoMeiYuan": "IntListJingHaoMeiYuan",
    "IntSpecXiaHuaJinHao": "IntSpecXiaHuaJinHao",
    "IntTupleList": "IntTupleList",
}

def get_data_type(key):
    if key in dataTypeDic:
        return dataTypeDic[key]
    elif key in dataCommonTypeDic:
        return dataCommonTypeDic[key]
    return None

##### main process #####
def Process(excel_Path):
    excel_file = excel_Path

    with open(excel_file, mode='r', encoding='utf-8') as file:
        # 创建csv阅读器
        csv_reader = csv.reader(file)
        # 读取表头
        #headers = next(csv_reader)
        #print(f"列名: {headers}")

        # 初始化一个列表来存储数据行
        data_rows = []

        # 遍历文件的前4行（包括表头，如果不需要表头，从下一行开始收集数据）
        for _ in range(5):  # 更改为range(1, 4)如果要排除表头
            try:
                row = next(csv_reader)
                data_rows.append(row)
            except StopIteration:
                # 如果文件中的行数不足5行，捕获异常并结束循环
                #print("已达到文件末尾，实际行数不足5行。")
                exit(0)
    # print("前5行数据（不包括表头）:")
    # exit(0)
        #for row in data_rows:
        #    print(row)
    proto_name = os.path.splitext(os.path.basename(excel_file))[0]
    base_name, _ = os.path.splitext(excel_file)
    proto_out_path = base_name + '.proto'
    Transition(data_rows,proto_name,proto_out_path)
    #return data_rows  # 返回收集到的数据行列表

def Transition(csvFileObj,proto_name,proto_out_path):
    # 假设csvFileObj是一个二维列表，类似于从CSV文件读取的数据
    columns_count = len(csvFileObj[2])

    code_lines = []
    #need_import_common = False  # 假设needImportCommon是一个标志，需要根据实际情况初始化

    for j in range(columns_count):
        cell_info1 = csvFileObj[1][j]
        cell_info2 = csvFileObj[2][j]
        cell_info3 = csvFileObj[3][j]

        if cell_info2 is None or cell_info3 is None:
            continue
        if not cell_info3:
            continue

        reg_num = re.compile("^[0-9]")

        if reg_num.match(cell_info3.strip()[0]):# or EDGenTableProto.HasChinese(cell_info3)
            continue

        if cell_info1 is not None:
            clean_info = cell_info1.replace('\n', '')
            comment = clean_info[:15] if len(clean_info) > 15 else clean_info
            code_lines.append(f"\t//{comment}")

        array = cell_info2.split('#')
        if len(array) < 1:
            code_lines.append(f"\tstring {cell_info3} = {j + 1};")
        else:
            data_type = get_data_type(array[0])
            if data_type is not None:
                code_lines.append(f"\t{data_type} {cell_info3} = {j + 1};")

        code_lines.append("")  # 对应于原C#中的换行

    # 拼接所有代码行
    generated_code = '\n'.join(code_lines)

    temp_info_proto_content = proto_str.format(
        proto_name.upper(),
        generated_code,
        #'import "table_common.proto";'
    )

    f = open(proto_out_path, 'wb')
    f.write(temp_info_proto_content.encode('utf-8'))
    f.close()


if __name__ == "__main__":
    table_name = None
    for arg in sys.argv[1:]:
        if table_name is None:
            table_name = arg
    # try:
    Process(table_name)
    # except BaseException as e:
    # print("打包错误")
    # exit(1)
    exit(0)
